package com.myblog.demo.config;

import com.myblog.demo.websocket.MyWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

/**
 * WebSocket 配置类
 */
@Configuration
@EnableWebSocket // 启动 WebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private MyWebSocketHandler myWebSocketHandler;

    /**
     * 通过这个注册方法，把创建好的 MyWebSocketHandler 类注册到具体的请求路径中
     *
     * @param registry WebSocketHandlerRegistry
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        //  当浏览器通过 WebSocket 请求的路径是 message_ctrl 的时候，会自动调用 MyWebSocketHandler 中的方法
        registry.addHandler(myWebSocketHandler, "/message_ctrl")
                // 通过注册这个特定的 HttpSession 拦截器，就可以把用户在 HttpSession 中添加的 Attribute 键值对也添加到 WebSocketSession 中
                .addInterceptors(new HttpSessionHandshakeInterceptor());
    }
}
